<template>
  <div>
    <div style="height:6vh;background-color:#fff;padding: 10px 20px;">
      <span style="line-height: 60px;font-size: 20px;">候选人管理</span>
      <el-button
          type="primary"
          v-if="getUser.level >= 20"
          style="float: right; margin-top: 13px;"
          @click="beforeAddResume">
        新增候选人
      </el-button>
    </div>

    <!-- 候选人弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form label-width="80px" label-position="top" :model="resumeForm" :rules="rules" ref="resumeForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="候选人姓名" prop="candidateName">
              <el-input v-model="resumeForm.candidateName" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="resumeForm.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="resumeForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应聘职位" prop="positionsId">
              <el-select v-model="resumeForm.positionsId" placeholder="请选择职位" style="width:100%">
                <el-option
                    v-for="pos in positionOptions"
                    :key="pos.id"
                    :label="pos.title"
                    :value="pos.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="简历文件" prop="resumeFile">
              <el-upload
                  class="upload-demo"
                  :action="uploadUrl"
                  name="file"
                  :on-success="handleUploadSuccess"
                  :before-upload="beforeUpload"
                  :show-file-list="false">
                <el-button v-if="!resumeForm.resumeFile" size="small" type="primary">点击上传</el-button>
                <span v-if="resumeForm.resumeFile" style="margin-left:10px">{{ fileName }}</span>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前状态" prop="status">
              <el-select v-model="resumeForm.status" placeholder="请选择状态" style="width:100%">
                <el-option label="已录用" :value="1"></el-option>
                <el-option label="已淘汰" :value="2"></el-option>
                <el-option label="待处理" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="面试时间" prop="interviewTime">
              <el-date-picker
                  v-model="resumeForm.interviewTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择面试时间"
                  style="width:100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="反馈意见" prop="feedback">
              <el-input v-model="resumeForm.feedback" placeholder="请输入反馈"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitResume">保存</el-button>
      </template>
    </el-dialog>

    <!-- 查询条件 -->
    <el-card style="margin: 20px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="候选人姓名">
          <el-input v-model="searchForm.candidateName" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option label="已录用" :value="1"></el-option>
            <el-option label="已淘汰" :value="2"></el-option>
            <el-option label="待处理" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadResumeList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card style="margin: 20px;">
      <el-table :data="resumeList">
        <el-table-column label="编号" type="index" align="center"></el-table-column>
        <el-table-column label="姓名" prop="candidateName" align="center"></el-table-column>
        <el-table-column label="联系电话" prop="phone" align="center"></el-table-column>
        <el-table-column label="应聘职位" align="center">
          <template #default="{row}">
            {{ getPositionName(row.positionsId) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="{row}">
            <el-tag :type="statusTagType(row.status)">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="面试时间" prop="interviewTime" align="center" width="180"></el-table-column>
        <el-table-column label="简历" align="center">
          <template #default="{row}">
            <a v-if="row.resumeFile"
               :href="'http://localhost:8080' + row.resumeFile"
                style="text-decoration: none;"
                target="_blank">
                <el-button size="small" type="text">查看简历</el-button>
            </a>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{row}">
            <el-button link type="text" @click="editResume(row)">编辑</el-button>
            <el-button link type="text" @click="deleteResume(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[3, 4, 5]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          style="margin-top: 20px;">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { Message } from 'element-ui';
import qs from "qs";

export default {
  data() {
    return {
      getUser: this.$getUser(),
      dialogVisible: false,
      dialogTitle: '新增候选人',
      uploadUrl: this.$BASE_URL + '/v1/file/upload',
      resumeForm: {
        id: null,
        candidateName: '',
        phone: '',
        email: '',
        positionsId: null,
        resumeFile: '',
        status: 3,
        interviewTime: null,
        feedback: ''
      },
      rules: {
        candidateName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确' }
        ],
        positionsId: [{ required: true, message: '请选择应聘职位', trigger: 'change' }],
        resumeFile: [{ required: true, message: '请上传简历文件', trigger: 'blur' }]
      },
      searchForm: {
        candidateName: '',
        status: null
      },
      resumeList: [],
      positionOptions: [],
      pagination: {
        current: 1,
        size: 3,
        total: 0
      }
    };
  },
  computed: {
    fileName() {
      if (this.resumeForm.resumeFile) {
        return this.resumeForm.resumeFile.split('/').pop();
      }
      return '';
    }
  },
  mounted() {
    this.loadResumeList();
    this.loadPositions();
  },
  methods: {
    // 加载候选人列表
    loadResumeList() {
      const data = qs.stringify({
        pageCurrent: this.pagination.current,
        pageSize: this.pagination.size,
        ...this.searchForm
      });

      axios.get(this.$BASE_URL + '/v1/resume/list?'+data)
          .then(res => {
            if (res.data.state === 2000) {
              this.resumeList = res.data.data.resumeList;
              this.pagination.total = res.data.data.total;
            }
          });
    },

    // 加载职位列表
    loadPositions() {
      axios.get(this.$BASE_URL + '/v1/position/list')
          .then(res => {
            if (res.data.state === 2000) {
              this.positionOptions = res.data.data.positionList;
            }
          });
    },

    //
    handleUploadSuccess(res) {
      if (res.state === 2000) {
        this.resumeForm.resumeFile = res.data;
        Message.success('上传成功');
      }
    },

    beforeUpload(file) {
      const isPDF = file.type === 'application/pdf';
      const isWord = file.type === 'application/msword' ||
          file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      // const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isPDF && !isWord) {
        Message.error('只能上传Word/PDF文件');
        return false;
      }
      // if (!isLt10M) {
      //   Message.error('文件大小不能超过10MB');
      //   return false;
      // }
      return true;
    },

    // 状态显示格式化
    formatStatus(status) {
      const map = { 1: '已录用', 2: '已淘汰', 3: '待处理' };
      return map[status];
    },

    statusTagType(status) {
      const types = { 1: 'success', 2: 'warning', 3: 'info' };
      return types[status] || '';
    },

    // 获取职位名称
    getPositionName(positionId) {
      const position = this.positionOptions.find(p => p.id === positionId);
      return position ? position.title : '未知职位';
    },

    // 提交候选人数据
    submitResume() {
      this.$refs.resumeForm.validate(valid => {
        if (valid) {
          axios.post(this.$BASE_URL + '/v1/resume/save', qs.stringify(this.resumeForm))
              .then(res => {
                if (res.data.state === 2000) {
                  Message.success('操作成功');
                  this.dialogVisible = false;
                  this.loadResumeList();
                }
              });
        }
      });
    },

    // 新增候选人
    beforeAddResume() {
      this.dialogTitle = '新增候选人';
      this.dialogVisible = true;
      this.resumeForm = {
        id: null,
        candidateName: '',
        phone: '',
        email: '',
        positionsId: null,
        resumeFile: '',
        status: 3,
        interviewTime: null,
        feedback: ''
      };
    },

    // 编辑候选人
    editResume(row) {
      this.dialogTitle = '编辑候选人信息';
      this.resumeForm = {
        id: row.id,
        candidateName: row.candidateName,
        phone: row.phone,
        email: row.email,
        positionsId: this.getPositionName(row.positionsId),
        resumeFile: row.resumeFile,
        status: row.status,
        interviewTime: row.interviewTime,
        feedback: row.feedback
      };
      this.dialogVisible = true;
    },

    // 删除候选人
    deleteResume(id) {
      this.$confirm('确定删除该候选人记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        axios.post(this.$BASE_URL + `/v1/resume/delete/${id}`)
            .then(res => {
              if (res.data.state === 2000) {
                Message.success('删除成功');
                this.loadResumeList();
              }
            });
      });
    },

    // 重置查询
    resetSearch() {
      this.searchForm = {
        candidateName: '',
        status: null
      };
      this.pagination.current = 1;
      this.loadResumeList();
    },

    // 分页处理
    handleSizeChange(size) {
      this.pagination.size = size;
      this.loadResumeList();
    },

    handleCurrentChange(current) {
      this.pagination.current = current;
      this.loadResumeList();
    },

    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false;
      this.resumeForm = {
        id: null,
        candidateName: '',
        phone: '',
        email: '',
        positionsId: null,
        resumeFile: '',
        status: 3,
        interviewTime: null,
        feedback: ''
      };
    }
  }
};
</script>

<style scoped>

</style>